import React, { FC, useState } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { Button, Space, Divider, Tag, Popconfirm, Modal, message } from 'antd'
import { useRequest } from 'ahooks'
import {
  EditOutlined,
  LineChartOutlined,
  CopyOutlined,
  StarOutlined,
  DeleteOutlined,
  ExclamationCircleFilled,
} from '@ant-design/icons'

import styles from './QuestionCard.module.scss'

//引入更新单个试卷的请求
import { updateQuestionListService, duplicateQuestionListService } from '../services/question'

// 气泡确认框
// const enterConfirm = (e: React.MouseEvent<HTMLElement>) => {
//   console.log(e)
//   message.success('您点击了确定!')
// }

const enterCancel = (e: React.MouseEvent<HTMLElement>) => {
  console.log(e)
  message.success('您点击了确定!')
}

type PropsType = {
  _id: string // 服务端 mongodb ，自动，_id 不重复
  title: string
  isStar: boolean
  isPublished: boolean
  answerCount: number
  createdAt: string
}

const QuestionCard: FC<PropsType> = (props: PropsType) => {
  const nav = useNavigate()
  // 父组件传递的数据
  const { _id, title, createdAt, answerCount, isPublished, isStar } = props

  const { confirm } = Modal

  // 删除操作
  const [isDeletedState, setIsDeletedState] = useState(false)
  const { loading: deleteLoading, run: delQuestion } = useRequest(
    async () => await updateQuestionListService(_id, { isDeleted: true }),
    {
      manual: true,
      onSuccess() {
        message.success('删除成功!')
        setIsDeletedState(true)
      },
    }
  )

  // model删除对话框
  const [isDel, setIsDel] = useState(true)
  function del() {
    setIsDel(false)
    confirm({
      title: '确定删除吗?',
      content: '删除后将无法恢复',
      icon: <ExclamationCircleFilled />,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onCancel: () => {
        setIsDel(true)
      },
      onOk: () => {
        delQuestion()
        setIsDel(isDel)
      },
    })
  }

  // 修改标星
  const [isStartState, setIsStartState] = useState(isStar)
  const { loading: changeStarLoading, run: changeStar } = useRequest(
    async () => {
      await updateQuestionListService(_id, {
        isStar: !isStartState,
      })
    },
    {
      manual: true,
      onSuccess() {
        setIsStartState(!isStartState) //更新state成功
        message.success('已更新')
      },
    }
  )

  //复制
  const { loading: duplicateLoading, run: duplicate } = useRequest(
    async () => {
      const data = await duplicateQuestionListService(_id)
      return data //data结果就是onSuccess中的res接收
    },
    {
      manual: true,
      onSuccess(res) {
        console.log(56)
        message.success('复制成功')
        // nav(`/question/edit/${res.id}`)
      },
    }
  )

  //如果已经删除的问卷,就不要再渲染卡片
  if (isDeletedState) return null

  return (
    <div className={styles.container}>
      <div className={styles.title}>
        <div className={styles.left}>
          <Link to={isPublished ? `/question/stat/${_id}` : `/question/edit/${_id}`}>
            <Space>
              {isStartState && <StarOutlined style={{ color: 'red' }} />}
              {title}
            </Space>
          </Link>
        </div>
        <div className={styles.right}>
          <Space>
            {isPublished ? <Tag color="processing">已发布</Tag> : <Tag>未发布</Tag>}
            <span>答卷: {answerCount}</span>
            <span>{createdAt}</span>
          </Space>
        </div>
      </div>
      <Divider style={{ margin: '12px 0' }} />
      <div className={styles['button-container']}>
        <div className={styles.left}>
          <Space>
            <Button
              icon={<EditOutlined />}
              type="text"
              size="small"
              onClick={() => nav(`/question/edit/${_id}`)}
            >
              编辑问卷
            </Button>
            <Button
              icon={<LineChartOutlined />}
              type="text"
              size="small"
              onClick={() => nav(`/question/stat/${_id}`)}
              disabled={!isPublished}
            >
              问卷统计
            </Button>
          </Space>
        </div>
        <div className={styles.right}>
          <Space>
            <Button
              type="text"
              icon={<StarOutlined />}
              onClick={changeStar}
              disabled={changeStarLoading}
            >
              {isStartState ? '取消标星' : '标星'}
            </Button>
            <Popconfirm
              title="复制问卷"
              description="确认复制该问卷?"
              onConfirm={duplicate}
              okText="Yes"
              cancelText="No"
            >
              <Button type="text" icon={<CopyOutlined />} size="small" disabled={duplicateLoading}>
                复制
              </Button>
            </Popconfirm>

            <Button
              type="text"
              icon={<DeleteOutlined />}
              size="small"
              onClick={del}
              disabled={!isDel}
            >
              删除
            </Button>
          </Space>
        </div>
      </div>
    </div>
  )
}

export default QuestionCard
